<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2021/8/9
 * Time: 14:06
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);

namespace app\common\business;

use app\common\model\mysql\Setting as ModelObj;
use app\common\validate\Setting as ValidateObj;
use think\Exception;
use think\facade\Cache;
use think\facade\Log;

class Setting extends BusBase
{
    protected ?ModelObj $modelObj = null;
    protected ?ValidateObj $validateObj = null;
    //是否验证允许重复
    protected bool $repeat = false;
    //验证数据库重复字段
    protected string $repeat_string = 'title';

    public function __construct()
    {
        $this->modelObj = new ModelObj();
        $this->validateObj = new ValidateObj();
    }

    /**
     * @param array $data
     * @return bool
     * @throws Exception
     */
    public function add(array $data = []): bool
    {
        $this->valAdd($data);
        //查询是否存在 存在则更新 不存在则新增
        try {
            $setting = $this->modelObj->getSettingByFind();
        } catch (\Exception $e) {
            Log::error($e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            throw new Exception("查询错误");
        }
        $data['update_time'] = time();
        if ($setting) {
            try {
                $res = $this->modelObj->updateById($setting['id'], $data);
            } catch (\Exception $e) {
                Log::error($e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
                throw new Exception("更新失败");
            }
        } else {
            $res = $this->modelObj->insertDataByInsertId($data);
        }

        if ($res) {
            Cache::delete('Cache_setting_name');
            return true;
        } else {
            return false;
        }
    }

    public function getSetting()
    {
        $setting = $this->modelObj->getSettingByFind('*');
        if ($setting) {
            return $setting->toArray();
        } else {
            return [];
        }
    }

}